<template>
  <div>
    <h3>案例 - todolist</h3>

    <!-- 案例的核心结构 -->
    <div class="todo-container">
      <div class="todo-wrap">
        <!-- 1. 头部的输入框 -->
        <Search :add="addItem" />

        <!-- 2. 列表项 -->
        <TaskList
          :list="taskList"
          :delItem="deleteItem"
          :changeItem="changeState"
        />

        <!-- 3. 底部布局 -->
        <Footer
          :list="taskList"
          :handlerDone="delAllDone"
          :changeIpt="changeAll"
        />
        <!-- footer 是 HTML5 中自带的标签 -->
      </div>
    </div>
  </div>
</template>

<script>
import Search from '../../components/Search.vue'
import TaskList from '../../components/TaskList.vue'
import Footer from '../../components/Footer.vue'
// 这个包，用于随机创建一个id
import { nanoid } from 'nanoid'

export default {
  data() {
    return {
      taskList: [
        { id: nanoid(), name: '和迪丽热巴打游戏', isDone: false },
        { id: nanoid(), name: '和古力娜扎吃饭', isDone: true },
        { id: nanoid(), name: '和马尔扎哈决战', isDone: true },
        { id: nanoid(), name: '和易烊千玺一起考试', isDone: false }
      ]
    }
  },
  methods: {
    // 1. 添加任务
    addItem(val) {
      this.taskList.unshift({
        id: nanoid(),
        name: val,
        isDone: false
      })
    },
    // 2. 删除任务
    deleteItem(id) {
      // 把符合id的数据去掉
      this.taskList = this.taskList.filter((item) => item.id !== id)
    },
    // 3. 改变任务状态
    changeState(id) {
      // 找到对应id的那一项，状态取反
      const curItem = this.taskList.find((item) => item.id === id)
      curItem.isDone = !curItem.isDone
    },
    // 4. 删除所有已完成的任务
    delAllDone() {
      // 过滤出没有完成的任务，重新给任务列表赋值
      this.taskList = this.taskList.filter((item) => !item.isDone)
    },
    // 5. 改变所有任务的状态
    changeAll(bool) {
      // 遍历当前的任务，把传入的布尔值进行赋值
      this.taskList.forEach((item) => (item.isDone = bool))
    }
  },
  components: {
    Search,
    TaskList,
    Footer
  }
}
</script>

<style lang="less">
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
